package p.wechat.zwapi.config;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import p.wechat.zwapi.api.WeChatApi;
import p.wechat.zwapi.api.impl.WeChatApiUtil;

import java.net.URI;
import java.net.URISyntaxException;

@Slf4j
@Component
public class WebSocketConfig {
    public static final String WS_LOCALHOST_2222 = "ws://localhost:2222";
    public static final String HTTPURL = "http://localhost:2222";
    public static WeChatApi wechatApi = new WeChatApiUtil();
    WebSocketClient webSocketClient;

    @Bean
    public WebSocketClient webSocketClient() {
        try {
            get();
            return webSocketClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private WebSocketClient getWebSocketClient() throws URISyntaxException {
        return new WebSocketClient(new URI(WS_LOCALHOST_2222), new Draft_6455()) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                log.info("[websocket] 连接成功");
            }

            @Override
            public void onMessage(String message) {
                try {
                    wechatApi.receivedTheNews(message);
                } catch (Throwable e) {
                    e.printStackTrace();
                } finally {
                    WeChatApi.LOCAL.remove();
                }
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                log.info("[websocket] 退出连接");
                get();
            }

            @Override
            public void onError(Exception ex) {
                log.info("[websocket] 连接错误={}", ex.getMessage());
                ThreadUtil.sleep(1000);
                get();
            }
        };
    }

    private void get() {
        try {
            webSocketClient = getWebSocketClient();
            webSocketClient.connect();
            webSocketClient.setConnectionLostTimeout(0);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

}